package io.renren.servlet;

import io.renren.entity.JxComputyDeviceEntity;
import io.renren.entity.JxLaboratoryEntity;
import io.renren.entity.JxStudentScheduleEntity;
import io.renren.service.JxComputyDeviceService;
import io.renren.service.JxLaboratoryService;
import io.renren.service.JxStudentScheduleService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet(urlPatterns = "/serv/*")
public class ResponseDemo2  extends HttpServlet {
    @Autowired
    private JxLaboratoryService jxLaboratoryService;

    @Autowired
    private JxComputyDeviceService jxComputyDeviceService;

     @Autowired
     private JxStudentScheduleService  jxStudentScheduleService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置状态码为302
        resp.setStatus(302);
        // 动态获取虚拟目录，以后修改虚拟目录的时候就不用了修改代码
        String keys=req.getParameterMap().get("key")[0].toString();
        String[] texts=keys.split("a");
        Long timeStemp=Long.parseLong(texts[0]);
        Long studentId=Long.parseLong(texts[1]);
        Long deviceId=Long.parseLong(texts[2]);
        Long scheduleId=Long.parseLong(texts[3]);
        JxComputyDeviceEntity deviceEntity=jxComputyDeviceService.getById(deviceId);
        JxStudentScheduleEntity studentSchedule=jxStudentScheduleService.getById(scheduleId);
        deviceEntity.setUseStatus("1");   //  正在使用状态
        studentSchedule.setStudyStatus("1");  //  正在进行
        Long laboratoryId=deviceEntity.getLaboratoryId();
        JxLaboratoryEntity laboratoryEntity=jxLaboratoryService.getById(laboratoryId);
        if(null!=deviceEntity&&null!=laboratoryEntity){
       // 设置响应头location
            if((timeStemp-new Date().getTime())>0){
                jxComputyDeviceService.saveOrUpdate(deviceEntity);
                jxStudentScheduleService.saveOrUpdate(studentSchedule);
                String url="http://"+laboratoryEntity.getInternetIp()+":"+deviceEntity.getPort();
                resp.setHeader("location",url);
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
